/**
 * 管理员管理
 */

//导入相应的库
import express from 'express';

//导入数据库连接
import conn from './../db/db'
import config from '../src/config';
import md5 from 'blueimp-md5'
const S_KEY = '@WaLQ1314?.LqFtK.Com.#'; // 盐



/**
 * 管理员登录
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function adminLogin(req,res){
    const account = req.body.account;
    const pwd = req.body.pwd;
    const md5Pwd = md5(md5(req.body.pwd) + S_KEY);
    if(!account || !pwd){
        res.json({error_code: 0, message: "账号和密码不得为空！"});
    }
    let sqlStr = "SELECT * FROM administrators WHERE account = '" + account + "'";
    conn.query(sqlStr, (error, results, fields) => {
        if(error){
            console.log(error);
            res.json({error_code: 0, message: "服务器内部错误！"});
        }else if(results[0]){
            let user = JSON.parse(JSON.stringify(results[0]));
            if(md5Pwd === user['pwd']){
                req.session.adminId = user['id'];
                res.json({success_code: 200, message: "登录成功！"});
            }else{
                res.json({error_code: 0, message: "密码错误！"});
            }
        }else{
            res.json({err_code: 0, message: "用户不存在！"});
        }
    });
}

/**
 * 管理员退出
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function adminLogout(req,res){
    console.log(req.session.adminId)
    delete  req.session.adminId;
	
    res.json({
        success_code: 200,
        message: "退出登录成功"
    });
}
export default {
  adminLogin,
  adminLogout

}